$(function() {
	"use strict";
	
	var initRoleTable = function () {

        var table = $('#role_table');

        table.DataTable({
        	"searching": false,
            "language": {
                "emptyTable": "暂无数据",
                "loadingRecords": "请稍候 - 数据加载中...",
                "info": "显示 _START_ 到 _END_ 共 _TOTAL_ 条记录",
                "infoEmpty": "",
                "infoFiltered": "",
                "lengthMenu": "_MENU_",
                "zeroRecords": "暂无数据",
                "paginate": {
                    "previous":"上一页",
                    "next": "下一页",
                    "last": "最后一页",
                    "first": "第一页"
                }
            },
            "ordering": false,
            "lengthChange":false,
            "pageLength": 20,
            "pagingType": "simple_numbers",
            "serverSide": true,
            "ajax": {
                url: context+"/console/role/list",
                type: 'POST',
                dataSrc: 'roleList'
            },
            "columns": [
                { "data": "roleKey" },
                { "data": "roleName" },
                { "data": "roleId",
                  "width":200,
                  "render": function ( data, type, full, meta ) {
                    return '<a href="javascript:;" class="btn btn-default btn-sm edit" data-edit-id='+data+' title="编辑角色"><i class="fa fa-edit"></i>  </a>&nbsp;'+
                    	   '<a href="javascript:;" class="btn btn-danger btn-sm remove" data-remove-id="'+data+'" title="删除角色"><i class="fa fa-remove"></i> </a>&nbsp;'+
                    	   '<a href="javascript:;" class="btn btn-success btn-sm query" data-query-id="'+data+'" data-query-name="'+full.roleName+'" title="角色对象管理"><i class="fa fa-search"></i>  </a>&nbsp;'
                  }
                }
            ]
        });
        
    }
	
	var initRoleObjTable = function () {

        var table = $('#role_obj_table');

        table.DataTable({
        	"searching": false,
            "language": {
                "emptyTable": "暂无数据",
                "loadingRecords": "请稍候 - 数据加载中...",
                "infoEmpty": "",
                "infoFiltered": "",
                "zeroRecords": "暂无数据"
            },
            "ordering": false,
            "lengthChange":false,
            "paging": false,
            "serverSide": true,
            "ajax": {
                url: context+"/console/role/obj/list",
                type: 'POST',
                data:function(d){
                	d.roleId = $("input[name='selectRoleId']").val();
                },
                dataSrc: 'roleObjList'
            },
            "columns": [
                { "data": "objType",
                  "render":function( data, type, full, meta ){
                	if(data=='G')
                		return '机构';
                	if(data=='U')
                		return '用户';
                } },
                { "data": "objName" },
                { "data": "roleObjId",
                  "render": function ( data, type, full, meta ) {
                    return '<a href="javascript:;" class="btn btn-danger btn-sm remove" data-remove-id="'+data+'" title="删除角色对象"><i class="fa fa-remove"></i> </a>&nbsp;'
                  }
                }
            ]
        });
        
        table.delegate('.remove','click',function(){
        	var removeId = $(this).data("removeId");
			
			$.ajax({
	            url:context+'/console/role/obj/delete/'+removeId,
	            type:'POST',
	            dataType:'json',
	            success:function(data,textStatus,jqXHR){
	                if(data.success){
	                	toastr["info"]("删除角色对象成功", "提示");
	                	$('#role_obj_table').DataTable().ajax.reload();
	                }else{
	                	toastr["error"]("删除角色对象异常", "提示");
	                }
	                
	            }
	        });
        });
    }
	
	var initAddRole = function(){
		$(".addRole").on('click',function(){
			var dialog = $("#roleAddDialog");
			var form = $("#roleForm",dialog);
			form[0].reset();
			dialog.modal();
		});
		
		$(".ok","#roleAddDialog").on('click',function(){
			var dialog = $("#roleAddDialog");
			var form = $("#roleForm",dialog);
			
			App.blockUI({
                target: '#roleAddDialogContent',
                boxed: true,
                message: '数据处理中...'
            });
			
			$.ajax({
	            url:context+'/console/role/save',
	            type:'POST',
	            data:form.serialize(),
	            dataType:'json',
	            success:function(data,textStatus,jqXHR){
	            	App.unblockUI('#roleAddDialogContent');
	                if(data.roleId){
	                	toastr["info"]("保存角色成功", "提示");
	                	$('#role_table').DataTable().ajax.reload();
	                	dialog.modal('hide');
	                }else{
	                	toastr["error"]("保存角色异常", "提示");
	                }
	                
	            }
	        });
		});
	}
	
	var initEditRole = function(){
		$("#role_table").delegate('.edit','click',function(){
			
			var editId = $(this).data("editId");
			
			var dialog = $("#roleEditDialog");
			var form = $("#roleEditForm",dialog);
			form[0].reset();
			
			dialog.modal();
			App.blockUI({
                target: '#roleEditDialogContent',
                boxed: true,
                message: '数据加载中...'
            });
			$.ajax({
	            url:context+'/console/role/load/'+editId,
	            type:'POST',
	            dataType:'json',
	            success:function(data,textStatus,jqXHR){
	            	App.unblockUI('#roleEditDialogContent');
	                if(data.success){
	                	iTsai.form.deserialize(form,data.data)
	                }else{
	                	toastr["error"]("加载角色数据异常", "提示");
	                }
	                
	            }
	        });
			
		});
		
		$(".ok","#roleEditDialog").on('click',function(){
			var dialog = $("#roleEditDialog");
			var form = $("#roleEditForm",dialog);
			
			App.blockUI({
                target: '#roleEditDialogContent',
                boxed: true,
                message: '数据处理中...'
            });
			
			$.ajax({
	            url:context+'/console/role/save',
	            type:'POST',
	            data:form.serialize(),
	            dataType:'json',
	            success:function(data,textStatus,jqXHR){
	            	App.unblockUI('#roleEditDialogContent');
	                if(data.roleId){
	                	toastr["info"]("保存角色成功", "提示");
	                	$('#role_table').DataTable().ajax.reload();
	                	dialog.modal('hide');
	                }else{
	                	toastr["error"]("保存角色异常", "提示");
	                }
	                
	            }
	        });
		});
		
	}
	
	var initRemoveRole = function(){
		$("#role_table").delegate('.remove','click',function(){
			
			var removeId = $(this).data("removeId");
			
			$.ajax({
	            url:context+'/console/role/delete/'+removeId,
	            type:'POST',
	            dataType:'json',
	            success:function(data,textStatus,jqXHR){
	                if(data.success){
	                	toastr["info"]("删除角色成功", "提示");
	                	$('#role_table').DataTable().ajax.reload();
	                }else{
	                	toastr["error"]("删除角色异常", "提示");
	                }
	                
	            }
	        });
			
		});
	}
	
	var initQueryRoleObj = function(){
		$("#role_table").delegate('.query','click',function(){
			
			var queryId = $(this).data("queryId");
			var queryName = $(this).data("queryName");
			
			$("#selectRoleName").html("["+queryName+"]");
			
			$("input[name='selectRoleId']").val(queryId);
			
			$('#role_obj_table').DataTable().ajax.reload();
			
			$(".selectRoleUser").removeClass('disabled');
			$(".selectRoleOrg").removeClass('disabled');
			
			$(".selectRoleUser").unbind('click').on('click',function(){
				var roleId = $("input[name='selectRoleId']").val();
				alert(roleId);
			});
			
			$(".selectRoleOrg").unbind('click').on('click',function(){
				var roleId = $("input[name='selectRoleId']").val();
				$("#orgSelectDialog").modal();
				
				$("#orgSelectTree").jstree().deselect_all();
				
				$.ajax({
		            url:context+'/console/role/objs',
		            type:'POST',
		            data:{roleId:roleId,objType:'G'},
		            dataType:'json',
		            success:function(data,textStatus,jqXHR){
		                if(data.success){
		                	var objIds = data.objIds.split(",");
		                	for(var i=0;i<objIds.length;i++){
		                		$("#orgSelectTree").jstree().select_node(objIds[i]);
		                	}
		                }else{
		                	toastr["error"]("加载角色对象异常", "提示");
		                }
		                
		            }
		        });
				
			});
			
			$(".selectRoleUser").unbind('click').on('click',function(){
				var roleId = $("input[name='selectRoleId']").val();
				$("#userSelectDialog").modal();
				
				$("#userSelectTree").jstree().deselect_all();
				
				$.ajax({
		            url:context+'/console/role/objs',
		            type:'POST',
		            data:{roleId:roleId,objType:'U'},
		            dataType:'json',
		            success:function(data,textStatus,jqXHR){
		                if(data.success){
		                	var objIds = data.objIds.split(",");
		                	for(var i=0;i<objIds.length;i++){
		                		$("#userSelectTree").jstree().select_node(objIds[i]);
		                	}
		                }else{
		                	toastr["error"]("加载角色对象异常", "提示");
		                }
		                
		            }
		        });
				
			});
			
			
		});
		
	}
	
	
	var initSelectOrgTree = function(){
		$("#orgSelectTree").jstree({
			"core" : {
				"themes" : {
					"responsive" : false
				},
				"check_callback" : true,
				'data' : {
					'url' : function(node) {
						return context + '/console/org/tree/data';
					},
					'data' : function(node) {
						return {
							'parent' : node.id
						};
					}
				}
			},
			"types" : {
				"default" : {
					"icon" : "fa fa-folder icon-state-warning icon-lg"
				},
				"file" : {
					"icon" : "fa fa-file icon-state-warning icon-lg"
				}
			},
			"plugins" : [ "checkbox","types" ]
		});
		
		
		$(".ok","#orgSelectDialog").on("click",function(){
			var objIds='';
			var objNames='';
			var selectObjs = $("#orgSelectTree").jstree().get_selected(true);
			for(var i=0;i<selectObjs.length;i++){
				if(objIds==''){
					objIds = selectObjs[i].id;
					objNames = selectObjs[i].text;
				}else{
					objIds = objIds+','+selectObjs[i].id;
					objNames =objNames+','+selectObjs[i].text;
				}
			}
			if(objIds!=''){
				var roleId = $("input[name='selectRoleId']").val();
				$.ajax({
		            url:context+'/console/role/objs/save',
		            type:'POST',
		            data:{objIds:objIds,objNames:objNames,objType:'G',roleId:roleId},
		            dataType:'json',
		            success:function(data,textStatus,jqXHR){
		                if(data.success){
		                	toastr["info"]("更新角色对象成功", "提示");
		                	$('#role_obj_table').DataTable().ajax.reload();
		                	$("#orgSelectDialog").modal('hide');
		                }else{
		                	toastr["error"]("更新角色对象异常", "提示");
		                }
		                
		            }
		        });
			}else{
				toastr["warning"]("请选择角色对象机构", "提示");
			}
		});
	}
	
	
	var initSelectUserTree = function(){
		$("#userSelectTree").jstree({
			"core" : {
				"themes" : {
					"responsive" : false
				},
				"check_callback" : true,
				'data' : {
					'url' : function(node) {
						return context + '/console/org/tree/data/user';
					},
					'data' : function(node) {
						return {
							'parent' : node.id
						};
					}
				}
			},
			"types" : {
				"default" : {
					"icon" : "fa fa-folder icon-state-warning icon-lg"
				},
				"file" : {
					"icon" : "fa fa-file icon-state-warning icon-lg"
				}
			},
			"plugins" : [ "checkbox","types" ],
			"checkbox" : {
			      "three_state" : false
			    }
		});
		
		
		$(".ok","#userSelectDialog").on("click",function(){
			var objIds='';
			var objNames='';
			var selectObjs = $("#userSelectTree").jstree().get_selected(true);
			for(var i=0;i<selectObjs.length;i++){
				if(objIds==''){
					objIds = selectObjs[i].id;
					objNames = selectObjs[i].text;
				}else{
					objIds = objIds+','+selectObjs[i].id;
					objNames =objNames+','+selectObjs[i].text;
				}
			}
			if(objIds!=''){
				var roleId = $("input[name='selectRoleId']").val();
				$.ajax({
		            url:context+'/console/role/objs/save',
		            type:'POST',
		            data:{objIds:objIds,objNames:objNames,objType:'U',roleId:roleId},
		            dataType:'json',
		            success:function(data,textStatus,jqXHR){
		                if(data.success){
		                	toastr["info"]("更新角色对象成功", "提示");
		                	$('#role_obj_table').DataTable().ajax.reload();
		                	$("#userSelectDialog").modal('hide');
		                }else{
		                	toastr["error"]("更新角色对象异常", "提示");
		                }
		                
		            }
		        });
			}else{
				toastr["warning"]("请选择角色对象用户", "提示");
			}
		});
	}
	

	initRoleTable();
	initRoleObjTable();
	initAddRole();
	initEditRole();
	initRemoveRole();
	initQueryRoleObj();
	initSelectOrgTree();
	initSelectUserTree();
	
});